package com.example.lym.syappandroid;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.baidu.android.pushservice.PushSettings;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.os.Message;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import model.User;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import baidupush.Utils;
import regular.IRegulation;

public class LoginActivity extends AppCompatActivity {

    private EditText userName, password;
    private CheckBox rem_pw, auto_login;
    private Button btn_login;

    private String userNameValue, passwordValue;
    private SharedPreferences sp;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        PushManager.startWork(getApplicationContext(),PushConstants.LOGIN_TYPE_API_KEY, IRegulation.API_KEY);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //获得实例对象
        sp = this.getSharedPreferences("userInfo",MODE_PRIVATE);
        userName = (EditText) findViewById(R.id.et_account);
        password = (EditText) findViewById(R.id.et_password);
        rem_pw = (CheckBox) findViewById(R.id.cb_mima);
        auto_login = (CheckBox) findViewById(R.id.cb_auto);
        btn_login = (Button) findViewById(R.id.bt_login);


        //判断记住密码多选框的状态
        if (sp.getBoolean("ISCHECK", false)) {
            //设置默认是记录密码状态
            rem_pw.setChecked(true);
            userName.setText(sp.getString("UACCOUNT", ""));
            password.setText(sp.getString("PASSWORD", ""));
            //判断自动登陆多选框状态
            if (sp.getBoolean("AUTO_ISCHECK", false)) {
                //设置默认是自动登录状态
                auto_login.setChecked(true);
                //跳转界面
                Intent intent = new Intent(LoginActivity.this, AlarmActivity.class);
                LoginActivity.this.startActivity(intent);

            }
        }

        // 登录监听事件
        btn_login.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                userNameValue = userName.getText().toString();
                passwordValue = password.getText().toString();

                if (userNameValue.equals("") || passwordValue.equals("")) {
                    Toast.makeText(LoginActivity.this, "账号和密码不能为空", Toast.LENGTH_SHORT).show();
                    //TO DO
                }
                else {
                    new Thread(new Runnable() {

                        //RequestBody requestBody = new FormBody.Builder().add("u_account", userNameValue).add("u_password", passwordValue).build();
                        @Override
                        public void run() {
                            OkHttpClient client = new OkHttpClient();
                            Request request = new Request.Builder().url("http://118.89.20.194:80/syapp/user/login?u_account="+userNameValue+"&u_password="+passwordValue).build();
                            // Request request = new Request.Builder().url("http://seeeven.me/ServerAndroidMVP/index/login?userid=aaa&password=222").build();
                            try {
                                Response response = client.newCall(request).execute();
                                String result = response.body().string();

                                //showResponse(result);
                                parseJSONWITHJSONObject(result);


                            } catch (IOException e) {
                                e.printStackTrace();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }
                    }).start();
                }



            }
        });


        //监听记住密码多选框按钮事件
        rem_pw.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (rem_pw.isChecked()) {

                    System.out.println("记住密码已选中");
                    sp.edit().putBoolean("ISCHECK", true).commit();

                } else {

                    System.out.println("记住密码没有选中");
                    sp.edit().putBoolean("ISCHECK", false).commit();

                }

            }
        });

        //监听自动登录多选框事件
        auto_login.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (auto_login.isChecked()) {
                    System.out.println("自动登录已选中");
                    sp.edit().putBoolean("AUTO_ISCHECK", true).commit();

                } else {
                    System.out.println("自动登录没有选中");
                    sp.edit().putBoolean("AUTO_ISCHECK", false).commit();
                }
            }
        });



    }


    private void parseJSONWITHJSONObject(String jsonData) throws JSONException {
//        Toast.makeText(LoginActivity.this,jsonData , Toast.LENGTH_LONG).show();

//        JSONArray jsonArray = new JSONArray(jsonData);
        JSONObject jsonObject=new JSONObject(jsonData);
        String resultcode=jsonObject.getString("resultCode");



        // System.out.print(u_id);

        if(resultcode.equals("1001")){
            //登陆成功
            //u_idb本地存储
            int u_id=jsonObject.getInt("data");
            System.out.println(u_id);
            User.setU_id(u_id);
            loginSuccess();
        }
        else{
            //登录失败
            loginFail();
        }
    }
    private void showResponse(final String result) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(LoginActivity.this, result, Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void loginSuccess()
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                //登录成功和记住密码框为选中状态才保存用户信息
                if (rem_pw.isChecked()) {
                    //记住用户名、密码、
                    Editor editor = sp.edit();
                    editor.putString("UACCOUNT", userNameValue);
                    editor.putString("PASSWORD", passwordValue);
                    editor.commit();
                }
                //跳转界面
                Intent intent = new Intent(LoginActivity.this, AlarmActivity.class);
                LoginActivity.this.startActivity(intent);
            }
        });

    }

    private void loginFail()
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(LoginActivity.this, "用户名或密码错误，请重新登录", Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    public void onStart() {
        super.onStart();



    }

    @Override
    public void onStop() {
        super.onStop();



    }

    }


